#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MAX_CMD 16
#define MAX_ARGC 16

typedef struct CMD
{
    int argc;
    char* argv[MAX_ARGC];
    char* input;
    char* output;
    int redirect;       //0无重定向 1重定向输入 2重定向输出 3重定向追加
}CMD;

CMD command[MAX_CMD];
int cmd_cnt;

void parse_command(char* cmd)
{
    int argc = 0;
    char* word = strtok(cmd, " ");
    while (word != NULL)
    {
        if (word[0] == '<')
        {
            command[0].redirect = 1;
            command[0].input = ++word;
        }
        else if (word[0] == '>')
        {
            if (word[1] != '>')
            {
                command[0].redirect = 2; 
                command[0].output = ++word; 
            }
            else
            {
                command[0].redirect = 3; 
                word+=2;
                command[0].output = word; 
            }  
            goto skip;          
        }

        command[0].argv[argc++] = word;
        word = strtok(NULL, " ");
    }
    skip:
       command[0].argc = argc;
}

void mysys(char *cmd)
{
    if (strcmp(command[0].argv[0], "exit") == 0)
    {
        exit(0);
    }
    else if (strcmp(command[0].argv[0], "cd") == 0)
    {
        chdir(command[0].argv[1]);
    }
    else if (strcmp(command[0].argv[0], "pwd") == 0)
    {
        char path[512];
        getcwd(path, sizeof(path));
        printf("%s\n", path);
    }
    else
    {
        pid_t pid = fork();

        int argc = command[0].argc;
        if (pid == 0)
        {
            int fd;
            switch (command[0].redirect)
            {
                case 1: 
                    fd = open(command[0].input, O_RDONLY);
                    dup2(fd, 0);
                    close(fd);
                    break;
                case 2: 
                    fd = open(command[0].output, O_CREAT | O_TRUNC | O_WRONLY);
                    dup2(fd, 1);
                    close(fd);
                    break;
                case 3: 
                    fd = open(command[0].output, O_CREAT | O_WRONLY | O_APPEND);
                    dup2(fd, 1);
                    close(fd);
                    break;
            }


            command[0].argv[argc] = (char *)malloc(sizeof(char)*128);
            command[0].argv[argc] = NULL;
            execvp(command[0].argv[0], command[0].argv);
        }
        else
        {
            wait(NULL);
        }
    }
}

int main()
{
    char buf[512];
    while (1)
    {
        write(1, ">", 2);
        memset(buf, 0, sizeof(buf));
        int cnt = read(0, buf, sizeof(buf));
        buf[cnt-1] = 0;

        parse_command(buf);

        mysys(buf);
    }
}